from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Length, EqualTo, ValidationError
from app.models import Admin, InviteCode
from datetime import datetime

class LoginForm(FlaskForm):
    username = StringField('用户名', validators=[
        DataRequired(message='请输入用户名'),
        Length(min=3, max=64, message='用户名长度必须在3-64个字符之间')
    ])
    password = PasswordField('密码', validators=[
        DataRequired(message='请输入密码'),
        Length(min=6, max=128, message='密码长度必须在6-128个字符之间')
    ])
    submit = SubmitField('登录')

class RegisterForm(FlaskForm):
    username = StringField('用户名', validators=[
        DataRequired(message='请输入用户名'),
        Length(min=3, max=64, message='用户名长度必须在3-64个字符之间')
    ])
    password = PasswordField('密码', validators=[
        DataRequired(message='请输入密码'),
        Length(min=6, max=128, message='密码长度必须在6-128个字符之间')
    ])
    confirm_password = PasswordField('确认密码', validators=[
        DataRequired(message='请确认密码'),
        EqualTo('password', message='两次输入的密码不一致')
    ])
    invite_code = StringField('邀请码', validators=[
        DataRequired(message='请输入邀请码'),
        Length(min=6, max=32, message='邀请码长度必须在6-32个字符之间')
    ])
    submit = SubmitField('注册')
    
    def validate_username(self, field):
        if Admin.query.filter_by(username=field.data).first():
            raise ValidationError('该用户名已被注册')
    
    def validate_invite_code(self, field):
        # 检查邀请码是否存在于数据库中且未被使用
        invite_code = InviteCode.query.filter_by(code=field.data).first()
        if not invite_code:
            raise ValidationError('邀请码无效')
        if invite_code.is_used:
            raise ValidationError('该邀请码已被使用') 